<?php

class SQLSelect extends SQLInstruction {

    private $columns = array();
    private $joins = array();

    public function addColumn($column) {
        $this->columns[] = $column;
    }

    public function addColumns($columns) {
        foreach ($columns as $column) {
            $this->columns[] = $column;
        }
    }

    public function addJoin(Join $join) {
        $this->joins[] = $join;
    }

    public function getInstruction() {
        $sql = 'SELECT ' . implode(',', $this->columns) . ' FROM ' . $this->entity . ' ' . $this->alias;

        if (isset($this->joins[0])) {
            foreach ($this->joins as $Join) {
                $sql .= ' ' . $Join->getInstruction();
            }
        }

        if (isset($this->criteria)) {
            $expression = $this->criteria->dump();
            if (isset($expression[0])) {
                $sql .= " WHERE {$expression}";
            }

            $order = $this->criteria->getProperty('order');
            $limit = $this->criteria->getProperty('limit');
            $offset = $this->criteria->getProperty('offset');

            if (isset($order)) {
                $sql .= ' ORDER BY ' . $order;
            }
            if (isset($limit)) {
                $sql .= ' LIMIT ' . $limit;
            }
            if (isset($offset)) {
                $sql .= ' OFFSET ' . $offset;
            }
        }
        return $sql;
    }

    /**
     *
     * @return PDO::Statements
     */
    public function execute() {
        $conn = Transaction::get();
        return $conn->query($this->getInstruction());
    }

}

?>
